package cn.tjad.tjad2.module.document.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.qiandian.android.base.common.bean.CommonListBean;
import com.qiandian.android.base.fragment.BaseFragment;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.HttpId;
import com.qiandian.android.base.net.http.IDataCallBack;
import com.qiandian.android.base.widget.TJADTTitleView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.module.document.adapter.PermissionBodySelectAdapter;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.Department;
import cn.tjad.tjad2.data.bean.Member;
import cn.tjad.tjad2.listener.OnItemClickListener;
import cn.tjad.tjad2.utils.Tools;

public class PermissionBodySelectFragment extends BaseFragment implements IDataCallBack, OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;

    private PermissionBodySelectAdapter adapter;
    private int projectId;

    private final int LEVEL_1 = 0;
    private final int LEVEL_2 = 1;
    private final int LEVEL_3 = 2;

    private int currentLevel = LEVEL_1;

    private List<Serializable> level1List, level2List, level3List;

    @Override
    public View getContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.common_recylerview, null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        projectId = TjadApplication.getInstance().getSession().getProjectId();
        swipeRefreshLayout.setOnRefreshListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        adapter = new PermissionBodySelectAdapter(null);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        requestCompanyList();
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        super.setCustomerTitle(titleView);
        titleView.showRight(true);
        titleView.setRightText("完成");
    }

    public void requestCompanyList() {
        RemoteDataService.getMemberList(projectId, this);
    }

    @Override
    public void onTitleClick(int which) {
        switch (which) {
            case TJADTTitleView.TITLE_RIGHT:
                onFinishCheck();
                break;
            case TJADTTitleView.TITLE_LEFT:
                interceptBackPressed();
                break;
        }
    }

    private void onFinishCheck() {
        int position = adapter.getCheckedPosition();
        if (position == -1) {
            Tools.showToast("请选择一个对象");
            return;
        }
        Serializable data = adapter.getItemData(position);
        Intent intent = new Intent();
        intent.putExtra(Keys.BODY, data);
        getActivity().setResult(Activity.RESULT_OK, intent);
        getActivity().finish();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        adapter.onDestroy();
    }

    @Override
    public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
        if (httpId == HttpId.MEMBER_LIST) {
            if (!TextUtils.isEmpty(errorMsg)) {
                Tools.showToast(errorMsg);
            } else {
                Tools.showToast("获取成员列表失败!");
            }
            swipeRefreshLayout.setRefreshing(false);
        }
        return false;
    }

    @Override
    public void onDataRefresh(int httpId, Object responseBean) {
        if (httpId == HttpId.MEMBER_LIST) {
            CommonListBean<Member> bean = (CommonListBean<Member>) responseBean;
            if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                currentLevel = LEVEL_1;
                adapter.setCheckedPosition(-1);
                List<Serializable> list = new ArrayList<>();
                list.addAll(bean.result);
                level1List = list;
                adapter.updateData(list);
                adapter.notifyDataSetChanged();
            } else {
                Tools.showToast(bean.respMsg);
            }
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void onItemClick(View parentView, View itemView, int position) {
        Serializable serializable = adapter.getItemData(position);
        if (serializable instanceof Member
                && ((Member) serializable).departmentList != null
                && ((Member) serializable).departmentList.size() > 0) {
            List<Serializable> list = new ArrayList<>();
            list.addAll(((Member) serializable).departmentList);
            level2List = list;
            changeToLevel(LEVEL_2);
        } else if (serializable instanceof Department
                && ((Department) serializable).userList != null
                && ((Department) serializable).userList.size() > 0) {
            List<Serializable> list = new ArrayList<>();
            list.addAll(((Department) serializable).userList);
            level3List = list;
            changeToLevel(LEVEL_3);
        } else {
            adapter.setCheckedPosition(position);
        }
    }

    @Override
    public boolean interceptBackPressed() {
        if (currentLevel == LEVEL_2) {
            changeToLevel(LEVEL_1);
            return true;
        } else if (currentLevel == LEVEL_3) {
            changeToLevel(LEVEL_2);
            return true;
        } else {
            return super.interceptBackPressed();
        }
    }

    private void changeToLevel(int level) {
        if (level == LEVEL_1) {
            adapter.setCheckedPosition(-1);
            adapter.updateData(level1List);
            adapter.notifyDataSetChanged();
            currentLevel = level;
        } else if (level == LEVEL_2) {
            adapter.setCheckedPosition(-1);
            adapter.updateData(level2List);
            adapter.notifyDataSetChanged();
            currentLevel = level;
        } else if (level == LEVEL_3) {
            adapter.setCheckedPosition(-1);
            adapter.updateData(level3List);
            adapter.notifyDataSetChanged();
            currentLevel = level;
        }
    }

    @Override
    public void onRefresh() {
        requestCompanyList();
    }
}
